import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    shopCarNum: 0,
    shopCarId: []
  },
  mutations: {
    changeBuyNum (state, params) {
      const num = window.localStorage.getItem('buynum')
      window.localStorage.setItem('buynum', Number(num) + params[0])
      state.shopCarNum = window.localStorage.getItem('buynum') - 0

      if (!window.localStorage.getItem('buyId')) {
        const arr = []
        arr.push(params[1])
        window.localStorage.setItem('buyId', JSON.stringify(arr))
        state.shopCarId = JSON.parse(window.localStorage.getItem('buyId'))
        return
      }
      var arr = JSON.parse(window.localStorage.getItem('buyId'))
      const i = arr.findIndex(val => val.id === params[1].id)
      if (i === -1) {
        arr.push(params[1])
        window.localStorage.setItem('buyId', JSON.stringify(arr))
        state.shopCarId = JSON.parse(window.localStorage.getItem('buyId'))
      } else {
        arr[i].num += params[1].num
        window.localStorage.setItem('buyId', JSON.stringify(arr))
        state.shopCarId = JSON.parse(window.localStorage.getItem('buyId'))
      }
    },
    changeNum (state, params) {
      const num = window.localStorage.getItem('buynum')
      window.localStorage.setItem('buynum', Number(num) + params)
      state.shopCarNum = window.localStorage.getItem('buynum') - 0
    },
    carBuyNum (state, params) {
      var arr = JSON.parse(window.localStorage.getItem('buyId'))
      const i = arr.findIndex(val => val.id === params.id)
      arr[i].num = params.num
      let num = Number(window.localStorage.getItem('buynum'))
      num = 0
      arr.forEach(val => {
        num += val.num
        window.localStorage.setItem('buynum', num)
        state.shopCarNum = window.localStorage.getItem('buynum') - 0
      })
      window.localStorage.setItem('buyId', JSON.stringify(arr))
      state.shopCarId = JSON.parse(window.localStorage.getItem('buyId'))
    }
  },
  actions: {

  },
  modules: {
  },
  getters: {
  }
})
